// scanPay.js
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
const app = getApp()
var util = require("../../utils/util.js")

Page({
  /**
   * 页面的初始数据
   */
  data: {
    swiperbox: app.globalData.swiperbox,
    swiper: app.globalData.swiper,
    orderlist:[],
    sn:'',
    key:null,
    orderindex: null,
    paywayShow:false,
    paywayActions: [
      {
        id:1,
        name: '微信支付',
        className:'weixinPay'
      }, {
        id:2,
        name: '余额支付',
        subname: '剩余:￥-.--',
        disabled: false,
        className: 'surplusPay'
      }
    ],
    balance:null,
    orderid:''
  },
  audio:function(){
    var audioCtx = wx.createInnerAudioContext()
    const version = wx.getSystemInfoSync().SDKVersion;
    if (util.compareVersion(version, '2.3.0') >= 0) {
      wx.setInnerAudioOption({
        mixWithOther: true,
        obeyMuteSwitch: false
      })
    }
    audioCtx.src = "http://file.gcb360.com/taocan.mp3";
    audioCtx.play()
    audioCtx.onError(function(res){
      console.log(res)
    })
  },
  // 选择充电时长
  choosePay:function(e){
    var that = this;
    var key = e.currentTarget.dataset.key;
    var orderindex = e.currentTarget.dataset.index;
    that.setData({
      key:key,
      orderindex: orderindex
    })
  },
  // 打开支付方式列表
  paywayBtn:function(){
    var that = this;
    var price = that.data.orderlist[that.data.orderindex].price;
    var disabled = false;
    if (that.data.balance < price){
      disabled= true;
    }
    that.setData({ 
      paywayShow: true,
      ['paywayActions[1].subname']: '剩余:￥' + that.data.balance,
      ['paywayActions[1].disabled']: disabled,
     });

  },
  // 关闭支付方式列表
  wayClose:function() {
    this.setData({ paywayShow: false });
  },
  // 选择支付方式
  payWay: function (event){
    // 微信支付
    if(event.detail.id == 1){
      this.weixin();
    }else if(event.detail.id == 2){
      this.surplus()
    }
  },
  // 选择余额支付并获取密码
  surplus:function(){
    var that = this;
    var pwdMsg = {};
    var data = {
      id: that.data.orderlist[that.data.orderindex].id,
      sn: that.data.sn
    }
    app.post('order/createOrder', data).then((res) => {
      console.log(res)
      if (res.code == 200) {
        app.globalData.order = [];
        app.globalData.order.push(res.entity);
        var version = 2;
        var bluetoothIDs = '';
        if (that.data.writeId) {
          version = 3;
          that.writeData(res.entity.passwd);
          bluetoothIDs = {
            deviceId: that.data.deviceId,
            servicesUUID: that.data.servicesUUID,
            readId: that.data.readId,
            writeId: that.data.writeId
          }
        }
        pwdMsg = {
          totalTime: res.entity.time,
          time: res.entity.time * 1000,
          pwd: res.entity.passwd
        }
        wx.navigateTo({
          url: '../charging/charging?sn=' + that.data.sn + '&pwdMsg=' + JSON.stringify(pwdMsg) + '&orderid=' + res.entity.id + '&version=' + version + '&bluetoothIDs=' + JSON.stringify(bluetoothIDs) + '&shopname=' + res.entity.shop.shopname,
        })
      } else if(res.code == 500) {
        var entity = res.entity;
        wx.showModal({
          title: '提示',
          content: '您还有一笔订单没有结束，请问是否结束订单？（结束订单无法再次获取密码，但如需获取密码需要重新支付生成订单）',
          confirmText:'结束订单',
          success:res=>{
            if(res.confirm){
              that.setData({
                orderid: entity.id
              })
              that.endOrder();
            }
          }
        })
      } else if(res.code == 409) {//设备在充电
        Toast.loading(res.message);
      } else {
        wx.showToast({
          title: '获取失败',
        })
      }
    }).catch((errMsg) => {
      console.log(errMsg);
    })
  },
  weixin: function () {
    var that = this;
    var data = { 
      id: that.data.orderlist[that.data.orderindex].id,
      sn: that.data.sn
    };
    var orderId = '';
    var devicesn = '';
    app.post("order/weixinPay", data).then((res) => {
      if (res.code == 200) {
        orderId = res.entity.id;
        devicesn = res.entity.devicesn;
        // app.globalData.order = [];
        // app.globalData.order.push(res.entity);
        wx.requestPayment({
          timeStamp: res.data.timeStamp,
          nonceStr: res.data.nonceStr,
          signType: 'MD5',
          package: res.data.package,
          paySign: res.data.paySign,
          success(res) {
            console.log('成功', res)
            that.getPasswd(orderId, devicesn);
          },
          fail(res) {
            console.log('失败', res)
            that.closeOrder(orderId)
          }
        })
      } else if (res.code == 500) {
        var entity = res.entity;
        wx.showModal({
          title: '提示',
          content: '您还有一笔订单没有结束，请问是否结束订单？（结束订单无法再次获取密码，但如需获取密码需要重新支付生成订单）',
          confirmText: '结束订单',
          success: res => {
            if (res.confirm) {
              that.setData({
                orderid: entity.id
              })
              that.endOrder();
            }
          }
        })
      } else if (res.code == 409) {//设备在充电
        Toast.loading(res.message);
      } else {
        wx.showToast({
          title: '获取失败',
        })
      }
    }).catch((errMsg) => {
      console.log(errMsg);//错误提示信息
    })
  },
  // 支付成功后获取密码
  getPasswd: function (orderId, devicesn) {
    var that = this;
    var pwdMsg ={}
    var data = {
      sn: devicesn,
      id: orderId
    };
    app.post('order/resetPasswd', data).then((res) => {
      console.log(res)
      if (res.code == 200) {
        app.globalData.order = [];
        app.globalData.order.push(res.entity);
        var version = 2;
        var bluetoothIDs = ''
        if (that.data.writeId) {
          version = 3;
          that.writeData(res.entity.passwd);
          bluetoothIDs = {
            deviceId: that.data.deviceId,
            servicesUUID: that.data.servicesUUID,
            readId: that.data.readId,
            writeId: that.data.writeId
          }
        }
        pwdMsg={
          totalTime: res.entity.time,
          time: res.entity.time * 1000,
          pwd: res.entity.passwd
        }
        
        wx.navigateTo({
          url: '../charging/charging?sn=' + that.data.sn + '&pwdMsg=' + JSON.stringify(pwdMsg) + '&orderid=' + res.entity.id + '&version=' + version + '&bluetoothIDs=' + JSON.stringify(bluetoothIDs) + '&shopname=' + res.entity.shop.shopname,
        })
      } else {
        wx.showToast({
          title: '获取失败，请重新获取',
        })
      }

    }).catch((errMsg) => {
      console.log(errMsg);
    })
  },
  //支付取消或者失败  关闭订单
  closeOrder: function (orderId){
    var that = this;
    var data = { id: orderId};
    app.post('order/closeWeixinOrder', data).then((res) => {
      if (res.code == 200) {
        Toast('已取消订单');
      } else {
        console.log(res)
      }
    }).catch((errMsg) => {
      console.log(errMsg);
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var orderlist = JSON.parse(options.orderlist);
    var advertise = JSON.parse(options.advertise);
    var sn = options.sn;
    var orderindex = orderlist.length - 1;
    if (advertise.length !== 0){
      app.globalData.swiper = advertise
    }
    if (options.bluetoothIDs){
      var bluetoothIDs = JSON.parse(options.bluetoothIDs)
      that.setData({
        deviceId: bluetoothIDs.deviceId,
        servicesUUID: bluetoothIDs.servicesUUID,
        readId: bluetoothIDs.readId,
        writeId: bluetoothIDs.writeId
      })
    }
    that.setData({
      swiper: app.globalData.swiper,
      orderlist:orderlist,
      sn:sn,
      orderindex: orderindex,
      key: orderlist[orderindex].gkey,
      shopname: options.shopname
    })
    // 获取余额
    var data = {};
    app.post('order/balance', data).then((res) => {
      if (res.code == 200) {
        console.log(`order/balance`,res)
        that.setData({
          balance: res.entity.balance
        })
      }
    }).catch((errMsg) => {
      console.log(errMsg);
    })
    that.audio();
  },
  // 向低功耗蓝牙设备特征值中写入二进制数据 6.0
  writeData(pwd) {
    var that = this;
    let buffer = util.hexStringToArrayBuffer(pwd);
    wx.writeBLECharacteristicValue({
      deviceId: that.data.deviceId,
      serviceId: that.data.servicesUUID,
      characteristicId: that.data.writeId,
      value: buffer,
      success: function (res) {
        // 设备返回的方法
        console.log('7.0writeBLECharacteristicValue success:', res.errMsg)
        that.readData()

      }, fail: function (res) {
        console.log('7.0writeBLECharacteristicValue--fail:', res, res.errMsg)
      }
    })
  },
  // 读取低功耗蓝牙设备的特征值的二进制数据值 7.0
  readData(uuid) {
    var that = this;
    wx.readBLECharacteristicValue({
      deviceId: that.data.deviceId,
      serviceId: that.data.servicesUUID,
      characteristicId: that.data.readId,
      success: function (res) {
        // 设备返回的方法
        console.log('readBLECharacteristicValue:', res.errCode)
        wx.onBLECharacteristicValueChange(function (res) {
          var nonceId = util.ab2hex(res.value)
          console.info("蓝牙测试返回的数据", res.value, nonceId);
          var nonceId = util.ab2hex(res.value)
        })
      }, fail: function (res) {
        console.log('readBLECharacteristicValue--fail:', res.errCode)
      }
    })
  },
  // 结束订单
  endOrder: function () {
    var that = this;
    var orderId = that.data.orderid;
    var data = { id: orderId };
    app.post('order/closeOrder', data).then((res) => {
      if (res.code == 200) {
        Toast('已结束订单，如需充电，请重新扫码支付获取密码');
      }else{
        console.log(res)
      }
    }).catch((errMsg) => {
      console.log(errMsg);
    })

  },
  phone:function(){
    wx.makePhoneCall({
      phoneNumber: '400-060-2006'
    })
  },
})